package com.heima.admin.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.admin.dto.ChannelDto;
import com.heima.admin.entity.AdChannel;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.service.IAdChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2020-10-09
 */
@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements IAdChannelService {

    @Override
    public ResponseResult findListByName(ChannelDto dto) {
        // 根据名称模糊查询分页列表

        // 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 构建分页条件 参数 1 当前页 2 每页条数
        IPage<AdChannel> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<AdChannel> query = new LambdaQueryWrapper<>();
        // 判断name是否为空
        if (!StringUtils.isEmpty(dto.getName())) {
            // 参数 1 字段 2 值
            query.like(AdChannel::getName, dto.getName());
        }
        IPage<AdChannel> iPage = this.page(page, query);
        // 返回通用的分页响应对象
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), iPage.getRecords());
        return result;
    }

    @Override
    public ResponseResult saveChannel(AdChannel channel) {
        if (StringUtils.isEmpty(channel.getName())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        LambdaQueryWrapper<AdChannel> query = new LambdaQueryWrapper<>();
        query.eq(AdChannel::getName, channel.getName());
        int count = this.count(query);
        if (count<=0){
            this.save(channel);
        }
        return ResponseResult.okResult(channel.getId());
    }

    @Override
    public ResponseResult deleteChannel(Integer id) {
        AdChannel channel = this.getById(id);
        if (channel==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (channel.getStatus()){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_CAN_NOT_DELETE);
        }

        this.removeById(id);
        return ResponseResult.okResult();
    }
}